package com.ddwl.goods.service;

import com.ddwl.common.util.BeanConverUtils;
import com.ddwl.common.util.MySqlUtil;
import com.ddwl.common.util.UUIDGenerator;
import com.ddwl.goods.dao.ItemRateDao;
import com.ddwl.goods.dao.ItemRateMediaDao;
import com.ddwl.goods.model.ItemRate;
import com.ddwl.goods.model.ItemRateMedia;
import com.ddwl.schema.bo.base.PageBo;
import com.ddwl.schema.bo.goods.ItemRateBo;
import com.ddwl.schema.bo.goods.ItemRateMediaBo;
import com.ddwl.schema.bo.goods.ItemRatePageBo;
import com.ddwl.schema.vo.base.PageVo;
import com.ddwl.schema.vo.goods.ItemRateMediaVo;
import com.ddwl.schema.vo.goods.ItemRateVo;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author hemiaojun
 * @Date 2021/7/1 17:50
 */
@Service
public class ItemRateService {

    @Resource
    private ItemRateDao itemRateDao;
    @Resource
    private ItemRateMediaDao itemRateMediaDao;


    @Transactional(rollbackFor = Exception.class)
    public void rate(List<ItemRateBo> itemRateBoList) {
        List<ItemRateMedia> itemRateMediaList = new ArrayList<>();
        itemRateBoList.forEach(itemRateBo -> {
            itemRateBo.setId(UUIDGenerator.getShortUUID());
            List<ItemRateMediaBo> itemRateMediaBoList = itemRateBo.getItemRateMediaBoList();
            if (!CollectionUtils.isEmpty(itemRateMediaBoList)) {
                itemRateMediaBoList.forEach(itemRateMediaBo -> itemRateMediaBo.setItemRateId(itemRateBo.getId()));
                itemRateMediaList.addAll(BeanConverUtils.convertBeanList(itemRateMediaBoList, ItemRateMedia.class));
            }
        });
        itemRateDao.insertList(BeanConverUtils.convertBeanList(itemRateBoList, ItemRate.class));
        itemRateMediaDao.insertList(itemRateMediaList);
    }

    public PageVo<ItemRateVo> page(PageBo<ItemRatePageBo> bo) {
        PageHelper.startPage(bo.getPage(), bo.getPageSize(), MySqlUtil.orderBy(bo.getSort(), bo.isAsc()));
        PageInfo<ItemRate> info = new PageInfo<>(itemRateDao.list(bo.getParam()));
        List<ItemRateVo> list = BeanConverUtils.convertBeanList(info.getList(), ItemRateVo.class);
        return new PageVo<>(info.getTotal(), bo.getPage(), bo.getPageSize(), list);
    }

    public ItemRateVo get(String id) {
        ItemRate itemRate = itemRateDao.selectByPrimaryKey(id);
        ItemRateVo vo = BeanConverUtils.convertBean(itemRate, ItemRateVo.class);
        List<ItemRateMedia> mediaList = itemRateMediaDao.listByItemRateId(id);
        if (!CollectionUtils.isEmpty(mediaList)) {
            vo.setItemRateMediaVoList(BeanConverUtils.convertBeanList(mediaList, ItemRateMediaVo.class));
        }
        return vo;
    }

}
